package com.example.no1admin.search.service.impl;


import com.example.no1admin.pojo.vo.route.RouteListItemVO;
import com.example.no1admin.restful.JsonPage;
import com.example.no1admin.search.entity.RouteForES;
import com.example.no1admin.search.repo.RouteForESRepository;
import com.example.no1admin.search.service.ISearchService;
import com.example.no1admin.service.IRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements ISearchService {

    @Autowired
    private IRouteService routeService;

    @Autowired
    private RouteForESRepository routeRepository;



    @Override
    public JsonPage<RouteForES> search(String keyword, Integer page, Integer pageSize) {
        Page<RouteForES> spus = routeRepository.querySearch(keyword, PageRequest.of(page-1,pageSize));
        JsonPage<RouteForES> jsonPage = new JsonPage<>();
        jsonPage.setPage(page);
        jsonPage.setPageSize(pageSize);
        jsonPage.setTotal(spus.getTotalElements());
        jsonPage.setTotalPage(spus.getTotalPages());
        jsonPage.setList(spus.getContent());
        return jsonPage;
    }

    //从数据库查
    @Override
    public void loadRouteByPage() {
        int i=1;
        int pages=0;
        do {
            JsonPage<RouteListItemVO> routeListItemVO = routeService.getRouteByPage(i,3);
            List<RouteForES> esRouteList = new ArrayList<>();
            for (RouteListItemVO route: routeListItemVO.getList()){
                RouteForES esRoute = new RouteForES();
                BeanUtils.copyProperties(route,esRoute);
                esRouteList.add(esRoute);
            }
            routeRepository.saveAll(esRouteList);
            log.info("成功加载第{}页数据",i);
            pages = routeListItemVO.getTotalPage();
            i++;
        }while (i<=pages);
    }
}
